/**
 * 配置管理器
 * 
 * 职责：
 * 1. 统一管理所有配置的访问
 * 2. 支持运行时配置覆盖
 * 3. 支持配置验证
 * 4. 支持配置持久化（可选）
 * 
 * @author AI Assistant
 * @date 2025-11-27
 */

import { GameConfig, GameConfigType } from './GameConfig';
import { getEnvironmentConfig, getCurrentEnvironment, Environment } from './EnvironmentConfig';
import { Log } from '../core/logger/LoggerGlobal';

/**
 * 配置覆盖类型
 */
type DeepPartial<T> = {
    [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};

/**
 * 配置管理器类（使用依赖注入）
 */
export class ConfigManager {
    /** 配置覆盖 */
    private configOverrides: DeepPartial<GameConfigType> = {};
    
    /** 是否已初始化 */
    private _initialized: boolean = false;
    
    constructor() {
        Log.general.debug('ConfigManager 已创建（DI）');
    }
    
    /**
     * 初始化配置管理器
     */
    init(): void {
        if (this._initialized) {
            Log.general.warn('配置管理器已初始化');
            return;
        }
        
        // 应用环境配置
        this.applyEnvironmentConfig();
        
        // 加载持久化配置（如果有）
        this.loadPersistedConfig();
        
        this._initialized = true;
        
        Log.styled('⚙️  配置管理器初始化完成', 'success');
        this.printCurrentConfig();
    }
    
    /**
     * 应用环境配置
     */
    private applyEnvironmentConfig(): void {
        const env = getCurrentEnvironment();
        const envConfig = getEnvironmentConfig();
        
        Log.general.info('应用环境配置', {
            environment: env,
            serverUrl: envConfig.serverUrl
        });
        
        // 根据环境覆盖配置
        this.override({
            Logger: {
                DEFAULT_LEVEL: envConfig.logLevel,
                ENABLE_COLOR: envConfig.enableColor,
                ENABLE_STACK_TRACE: envConfig.enableStackTrace,
            },
            Performance: {
                ENABLE_PERFORMANCE_STATS: envConfig.enablePerformanceStats,
                SHOW_FPS_STATS: envConfig.showFPS,
            },
            Debug: {
                ENABLE_DEBUG: envConfig.enableDebug,
                SHOW_FPS: envConfig.showFPS,
                ENABLE_GM_COMMANDS: envConfig.enableGM,
                ENABLE_HOT_RELOAD: envConfig.enableHotReload,
            },
            Network: {
                SERVER_URL: envConfig.serverUrl,
            },
            Resource: {
                ENABLE_PRELOAD: envConfig.enablePreload,
            }
        });
    }
    
    /**
     * 获取配置值
     */
    get<K extends keyof GameConfigType>(category: K): Readonly<GameConfigType[K]> {
        // 合并默认配置和覆盖配置
        const defaultConfig = GameConfig[category];
        const override = this.configOverrides[category];
        
        if (override) {
            return { ...defaultConfig, ...override } as GameConfigType[K];
        }
        
        return defaultConfig;
    }
    
    /**
     * 获取具体配置项
     */
    getValue<K extends keyof GameConfigType, V extends keyof GameConfigType[K]>(
        category: K,
        key: V
    ): GameConfigType[K][V] {
        const categoryConfig = this.get(category);
        return categoryConfig[key];
    }
    
    /**
     * 覆盖配置
     */
    override(overrides: DeepPartial<GameConfigType>): void {
        // 深度合并配置
        this.configOverrides = this.deepMerge(this.configOverrides, overrides);
        
        Log.general.debug('配置已覆盖', overrides);
    }
    
    /**
     * 重置配置覆盖
     */
    resetOverrides(): void {
        this.configOverrides = {};
        Log.general.info('配置覆盖已重置');
    }
    
    /**
     * 深度合并对象
     */
    private deepMerge<T>(target: T, source: DeepPartial<T>): T {
        const result = { ...target };
        
        for (const key in source) {
            const sourceValue = source[key];
            const targetValue = result[key];
            
            if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
                result[key] = this.deepMerge(targetValue as any, sourceValue) as any;
            } else {
                result[key] = sourceValue as any;
            }
        }
        
        return result;
    }
    
    /**
     * 验证配置
     */
    validate(): boolean {
        let isValid = true;
        
        // 验证性能配置
        const perf = this.get('Performance');
        if (perf.LOGIC_FPS <= 0 || perf.LOGIC_FPS > 120) {
            Log.general.error('无效的逻辑帧率', { fps: perf.LOGIC_FPS });
            isValid = false;
        }
        
        // 验证场景配置
        const scene = this.get('Scene');
        if (scene.DEFAULT_LAYERS.length === 0) {
            Log.general.error('场景层级不能为空');
            isValid = false;
        }
        
        // 验证音频配置
        const audio = this.get('Audio');
        if (audio.MASTER_VOLUME < 0 || audio.MASTER_VOLUME > 1) {
            Log.general.error('无效的主音量', { volume: audio.MASTER_VOLUME });
            isValid = false;
        }
        
        return isValid;
    }
    
    /**
     * 打印当前配置
     */
    printCurrentConfig(): void {
        const env = getCurrentEnvironment();
        
        Log.styled('━'.repeat(60), 'separator');
        Log.styled('⚙️  当前配置', 'title');
        Log.styled('━'.repeat(60), 'separator');
        
        Log.general.info(`环境: ${env}`);
        Log.general.info(`逻辑帧率: ${this.getValue('Performance', 'LOGIC_FPS')} FPS`);
        Log.general.info(`渲染帧率: ${this.getValue('Performance', 'RENDER_FPS')} FPS`);
        Log.general.info(`日志级别: ${this.getValue('Logger', 'DEFAULT_LEVEL')}`);
        Log.general.info(`调试模式: ${this.getValue('Debug', 'ENABLE_DEBUG') ? '开启' : '关闭'}`);
        Log.general.info(`服务器地址: ${this.getValue('Network', 'SERVER_URL')}`);
        
        Log.styled('━'.repeat(60), 'separator');
    }
    
    /**
     * 保存配置到本地存储（可选）
     */
    saveToLocalStorage(): void {
        try {
            const configStr = JSON.stringify(this.configOverrides);
            localStorage.setItem('game_config_overrides', configStr);
            Log.general.info('配置已保存到本地存储');
        } catch (error) {
            Log.general.error('保存配置失败', { error });
        }
    }
    
    /**
     * 从本地存储加载配置
     */
    private loadPersistedConfig(): void {
        try {
            const configStr = localStorage.getItem('game_config_overrides');
            if (configStr) {
                const overrides = JSON.parse(configStr);
                this.override(overrides);
                Log.general.info('已从本地存储加载配置');
            }
        } catch (error) {
            Log.general.warn('加载本地配置失败', { error });
        }
    }
    
    /**
     * 清除本地存储的配置
     */
    clearPersistedConfig(): void {
        localStorage.removeItem('game_config_overrides');
        Log.general.info('已清除本地存储的配置');
    }
    
    /**
     * 获取所有配置（调试用）
     */
    getAllConfig(): Readonly<GameConfigType> {
        return {
            Performance: this.get('Performance'),
            Scene: this.get('Scene'),
            Logger: this.get('Logger'),
            ECS: this.get('ECS'),
            Resource: this.get('Resource'),
            NodePool: this.get('NodePool'),
            CommandQueue: this.get('CommandQueue'),
            Network: this.get('Network'),
            Debug: this.get('Debug'),
            GameRule: this.get('GameRule'),
            Audio: this.get('Audio'),
        };
    }
}

/**
 * 使用说明：
 * 
 * ConfigManager 现在使用依赖注入，不再是单例。
 * 
 * 通过 DI 容器获取实例：
 * ```typescript
 * import { container, ServiceIdentifiers } from '../core/di';
 * const configManager = container.resolve<ConfigManager>(ServiceIdentifiers.ConfigManager);
 * ```
 * 
 * 使用示例：
 * 
 * ```typescript
 * import { configManager } from '../config/ConfigManager';
 * 
 * // 初始化配置管理器
 * configManager.init();
 * 
 * // 获取配置
 * const perfConfig = configManager.get('Performance');
 * const logicFPS = configManager.getValue('Performance', 'LOGIC_FPS');
 * 
 * // 运行时覆盖配置
 * configManager.override({
 *     Performance: {
 *         LOGIC_FPS: 30
 *     }
 * });
 * 
 * // 验证配置
 * if (!configManager.validate()) {
 *     console.error('配置验证失败');
 * }
 * 
 * // 保存配置
 * configManager.saveToLocalStorage();
 * ```
 */

